package com.free.semantic.common;

import com.free.semantic.core.IClone;
import org.apache.commons.collections4.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class RelationInstance implements IClone<RelationInstance> {

    private String name;

    private int instanceID;

    private List<RelationItem> relationItems;

    public RelationInstance(String name) {
        this.name = name;
    }

    public void reNameObjName(String sourceName, String updateName) {
        relationItems.forEach(item -> item.reNameObjName(sourceName, updateName));
    }

    public boolean removeRelationItem(RelationItem item) {
        for (int i = 0; i < relationItems.size(); i++) {
            if (relationItems.get(i).equals(item)) {
                relationItems.remove(i);
                return true;
            }
        }
        return false;
    }

    public void setParentToNull() {
        for (RelationItem relationItem : relationItems) {
            relationItem.setParentInstanceID(relationItem.getParentInstance().getInstanceID());
            relationItem.setParentInstance(null);
        }
    }


    @Override
    public RelationInstance clone() {
        RelationInstance instance = new RelationInstance(name);
        if (CollectionUtils.isEmpty(relationItems)) {
            return instance;
        }
        List<RelationItem> items = relationItems.stream().map(RelationItem::clone).collect(Collectors.toList());
        instance.setRelationItems(items);
        instance.setInstanceID(this.instanceID);
        return instance;
    }

    public List<String> findAllObjName() {
        Set<String> res = new HashSet<>();
        for (RelationItem relationItem : relationItems) {
            List<String> allNames = Stream.of(relationItem.getSourceObjectList(), Ls.of(relationItem.getDestObject()))
                    .flatMap(Collection::stream).map(RangeObj::getObjectName).distinct().collect(Collectors.toList());
            res.addAll(allNames);
        }
        return new ArrayList<>(res);
    }


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getInstanceID() {
        return instanceID;
    }

    public void setInstanceID(int instanceID) {
        this.instanceID = instanceID;
    }

    public List<RelationItem> getRelationItems() {
        return relationItems;
    }

    public void setRelationItems(List<RelationItem> relationItems) {
        this.relationItems = relationItems;
    }


}
